/**
 * @Author: ls-mac
 * @Date:   2018-11-11T19:48:09+08:00
 * @Last modified by:   ls-mac
 * @Last modified time: 2019-01-14 17:32:57
 */
import React, { PureComponent } from 'react';
import { Table, Input, InputNumber, Select, Form, Icon } from 'antd';
import styles from './index.less';

const FormItem = Form.Item;

const EditableContext = React.createContext();
let arrMaxLength = 1;

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);

const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  constructor(props) {
    super(props);
    const { dataIndex, record, selectData } = props;
    this.state = {
      dataIndex,
      record,
      selectData,
      reArr: [],
      optionsItems: [],
      index: 0,
      inDataObj: {},
    };
  }

  changeTdInput = (e, k, form) => {
    const {
      inDataObj,
      record: { key },
    } = this.state;
    inDataObj[`${key  }-${  k  }-weight`] = e.target.value;
    const lo = localStorage.getItem('SpecialTableInDataObj')
      ? JSON.parse(localStorage.getItem('SpecialTableInDataObj'))
      : {};
    const _OBJ = Object.assign(lo, inDataObj);
    localStorage.setItem('SpecialTableInDataObj', JSON.stringify(_OBJ));
    this.setState(inDataObj);
  };

  changeTdSelect = (e, k, form) => {
    const {
      inDataObj,
      record: { key },
    } = this.state;
    inDataObj[`${key  }-${  k  }-spec`] = e;
    const lo = localStorage.getItem('SpecialTableInDataObj')
      ? JSON.parse(localStorage.getItem('SpecialTableInDataObj'))
      : {};
    const _OBJ = Object.assign(lo, inDataObj);
    localStorage.setItem('SpecialTableInDataObj', JSON.stringify(_OBJ));
    this.setState(inDataObj);
  };

  // module count
  handleMinusIconClick = k => {
    const {
      inDataObj,
      record: { key },
    } = this.state;
    const { reArr } = this.state;
    let _arr = [];
    if (reArr instanceof Array) {
      _arr = reArr.map(v => {
        if (v) {
          if (v.key != k) return v;
        }
      });
    }
    delete inDataObj[`${key  }-${  k  }-weight`];
    delete inDataObj[`${key  }-${  k  }-spec`];

    const lo = localStorage.getItem('SpecialTableInDataObj')
      ? JSON.parse(localStorage.getItem('SpecialTableInDataObj'))
      : '';

    if (lo) {
      delete lo[`${key  }-${  k  }-weight`];
      delete lo[`${key  }-${  k  }-spec`];
      const _OBJ = Object.assign(lo, inDataObj);
      localStorage.setItem('SpecialTableInDataObj', JSON.stringify(_OBJ));
    }
    this.setState({ reArr: _arr, inDataObj });
  };

  // module select

  // module td
  createTdDom = form => {
    const { getFieldDecorator } = form;
    const {
      reArr,
      record,
      record: { dmPickupDispatchSpecList, key },
    } = this.state;

    const createSelect = (k, x) => {
      const { dataIndex, record, selectData, reArr } = this.state;
      const optionsItems = [];
      if (selectData instanceof Array) {
        selectData.map(v => {
          optionsItems.push(
            <Option value={v.value} key={v.key}>
              {v.name}
            </Option>
          );
        });
      }

      return (
        <Select onChange={e => this.changeTdSelect(e, k, form)} style={{ width: '160px' }}>
          {optionsItems}
        </Select>
      );
    };
    const createSelect0 = () => {
      const { dataIndex, record, selectData, reArr } = this.state;
      const optionsItems = [];
      if (selectData instanceof Array) {
        selectData.map(v => {
          optionsItems.push(
            <Option value={v.value} key={v.key}>
              {v.name}
            </Option>
          );
        });
      }

      return (
        <FormItem style={{ display: 'inline-block' }}>
          {getFieldDecorator('spec')(<Select style={{ width: '160px' }}>{optionsItems}</Select>)}
        </FormItem>
      );
    };

    const handleIconClick = () => {
      const _k = `B${  reArr.length++}`;
      reArr.push(
        <div key={_k}>
          {createSelect(_k)}
          <Input onChange={e => this.changeTdInput(e, _k, form)} style={{ width: '40px' }} />
          <span
            style={{ cursor: 'pointer', marginLeft: '8px' }}
            onClick={() => this.handleMinusIconClick(_k)}
          >
            <Icon type="minus-circle" />
          </span>
        </div>
      );

      this.setState({ index: this.state.index + 1, reArr });
    };
    const k0 = `A${  0}`;
    let arr = [
      <div key={k0}>
        {createSelect0()}
        <FormItem style={{ display: 'inline-block' }}>
          {getFieldDecorator('weight')(<Input style={{ width: '40px' }} />)}
        </FormItem>
        <span style={{ cursor: 'pointer', marginLeft: '8px' }} onClick={handleIconClick}>
          <Icon type="plus-circle" />
        </span>
      </div>,
    ];

    console.log(dmPickupDispatchSpecList);
    if (dmPickupDispatchSpecList instanceof Array) {
      // arr = dmPickupDispatchSpecList.map((v, i) => {
      //   return (
      //     <div key={'A' + i}>
      //       {createSelect(v.spec)}
      //       <Input style={{ width: '40px' }} defaultValue={v.weight} />
      //       <span style={{ cursor: 'pointer', marginLeft: '8px' }} onClick={this.handleIconClick}>
      //         <Icon type="plus-circle" />
      //       </span>
      //     </div>
      //   );
      // });
      arr = dmPickupDispatchSpecList.map(v => {
        if (v.spec) {
          return (
            <p>
              <span>{v.spec}</span>/<span>{v.shopSign}</span>
              &nbsp;&nbsp;
              <span>{v.weight}</span>
            </p>
          );
        }
      });
    }
    return [...arr, ...reArr];
  };

  newDoubleDeck = form => {
    const { getFieldDecorator } = form;
    const { editing, dataIndex, title, inputType, record, index, ...restProps } = this.props;
    const createEmpty = x => {
      const emptyDom = [];
      if (x) {
        for (let i = 0; i < x - 0; i++) {
          emptyDom.push(
            <span style={{ width: '100%', height: '26px', display: 'inline-block' }}>&nbsp;</span>
          );
        }
      }
      return emptyDom;
    };
    const redom = [];

    if (inputType === 'module') {
      redom.push(this.createTdDom(form));
    } else if (dataIndex instanceof Array) {
      if (dataIndex.length > arrMaxLength) {
        arrMaxLength = dataIndex.length;
      }
      redom.push(
        <FormItem className={styles.selectContainer}>
          {dataIndex.map(v => {
            return (
              <span style={{ width: '100%', height: '26px', display: 'inline-block' }}>
                {getFieldDecorator(v, {
                  initialValue: record[v] ? record[v].value : '',
                })(this.getInput(v))}
              </span>
            );
          })}
          {createEmpty(arrMaxLength - dataIndex.length)}
        </FormItem>
      );
    } else if (typeof dataIndex === 'string') {
      redom.push(
        <FormItem className={styles.selectContainer}>
          {getFieldDecorator(dataIndex, {
            initialValue: record[dataIndex] ? record[dataIndex].value : '',
          })(this.getInput(dataIndex))}
          {createEmpty(arrMaxLength - 1)}
        </FormItem>
      );
    }
    return redom;
  };

  getInput = dataIndex => {
    const { inputType, record, selectData } = this.props;
    if (inputType === 'select') {
      const Option = Select.Option;
      const optionsItems = [];
      if (selectData instanceof Array) {
        selectData.map(v => {
          optionsItems.push(
            <Option value={v.value} key={v.key}>
              {v.name}
            </Option>
          );
        });
      } else if (typeof selectData === 'object') {
        if (selectData[dataIndex]) {
          selectData[dataIndex].map(v => {
            optionsItems.push(
              <Option value={v.value} key={v.key}>
                {v.name}
              </Option>
            );
          });
        }
      }
      return (
        <Select
          disabled={record[dataIndex] ? record[dataIndex].disabled : false}
          style={{ width: '100%' }}
        >
          {optionsItems}
        </Select>
      );
    }
    return <Input disabled={record[dataIndex] ? record[dataIndex].disabled : false} />;
  };

  render() {
    const { editing, dataIndex, title, inputType, record, index, ...restProps } = this.props;

    return (
      <EditableContext.Consumer>
        {form => {
          const { getFieldDecorator } = form;
          if (record && !record.form) {
            record.form = form;
          }
          return <td {...restProps}>{editing ? this.newDoubleDeck(form) : restProps.children}</td>;
        }}
      </EditableContext.Consumer>
    );
  }
}

function initTotalList(columns) {
  const totalList = [];
  columns.forEach(column => {
    if (column.needTotal) {
      totalList.push({ ...column, total: 0 });
    }
  });
  return totalList;
}

class StandardTable extends PureComponent {
  constructor(props) {
    super(props);
    const { columns } = props;
  }

  componentWillReceiveProps(nextProps) {}

  render() {
    const {
      data: { list },
      loading,
      rowKey,
    } = this.props;

    arrMaxLength = 1;

    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };

    const columns = this.props.columns.map(col => {
      if (typeof col.hidden === 'function') {
        col.hidden = col.hidden();
      }
      if (col.hidden) {
        return {};
      }
      if (!col.editable) {
        return col;
      }

      return {
        ...col,
        onCell: record => ({
          record,
          selectData: col.selectData,
          inputType: col.inputType,
          dataIndex: col.dataIndex,
          title: col.title,
          editing: record.editable,
        }),
      };
    });
    return (
      <div className={styles.editableTable}>
        <Table
          loading={loading}
          components={components}
          dataSource={list}
          columns={columns}
          pagination={false}
        />
      </div>
    );
  }
}

export default StandardTable;
